// Copyright 2009 Google Inc. All Rights Reserved.

/**
 * @fileoverview Code for common functionality in home and canvas view.
 */

/**
 * User preferences.
 * @type {_IG_Prefs}
 */
var prefs = new _IG_Prefs();

/**
 * Timeout interval.
 * @const
 */
var TIME_OUT = 7000;

/**
 * Collection of information for all categories.
 * @type {Object}
 */
var categoryObj = [
  {
    'id': 4,
    'icon': 'http://assets.foodzie.com/media/catalog/category/' +
        'category_icon_cookie.png',
    'link': 'http://foodzie.com/bakery.html?ref=5',
    'desc': prefs.getMsg('bakery_desc')
  },
  {
    'id': 209,
    'icon': 'http://assets.foodzie.com/media/catalog/category/cheese.png',
    'link': 'http://foodzie.com/cheese-dairy.html?ref=5',
    'desc': prefs.getMsg('cheese_desc')
  },
  {
    'id': 6,
    'icon': 'http://assets.foodzie.com/media/catalog/category/chocolate.png',
    'link': 'http://foodzie.com/chocolate-candy.html?ref=5',
    'desc': prefs.getMsg('chocolate_desc')
  },
  {
    'id': 15,
    'icon': 'http://assets.foodzie.com/media/catalog/category/gift.png',
    'link': 'http://foodzie.com/food-gifts.html?ref=5',
    'desc': prefs.getMsg('gift_desc')
  },
  {
    'id': 7,
    'icon': 'http://assets.foodzie.com/media/catalog/category/coffee.png',
    'link': 'http://foodzie.com/coffee-tea-drinks.html?ref=5',
    'desc': prefs.getMsg('coffee_desc')
  },
  {
    'id': 8,
    'icon': 'http://assets.foodzie.com/media/catalog/category/honey.png',
    'link': 'http://foodzie.com/honey-jam.html?ref=5',
    'desc': prefs.getMsg('honey_desc')
  },
  {
    'id': 9,
    'icon': 'http://assets.foodzie.com/media/catalog/category/meat.png',
    'link': 'http://foodzie.com/meat-seafood.html?ref=5',
    'desc': prefs.getMsg('meat_desc')
  },
  {
    'id': 10,
    'icon': 'http://assets.foodzie.com/media/catalog/category/pantry.png',
    'link': 'http://foodzie.com/gourmet-pantry-staples-spices.html?ref=5',
    'desc': prefs.getMsg('pantry_desc')
  },
  {
    'id': 11,
    'icon': 'http://assets.foodzie.com/media/catalog/category/prepared.png',
    'link': 'http://foodzie.com/prepared-foods.html?ref=5',
    'desc': prefs.getMsg('prepared_desc')
  },
  {
    'id': 12,
    'icon': 'http://assets.foodzie.com/media/catalog/category/produce.png',
    'link': 'http://foodzie.com/produce.html?ref=5',
    'desc': prefs.getMsg('produce_desc')
  },
  {
    'id': 13,
    'icon': 'http://assets.foodzie.com/media/catalog/category/condiments.png',
    'link': 'http://foodzie.com/sauces-condiments.html?ref=5',
    'desc': prefs.getMsg('condiments_desc')
  },
  {
    'id': 14,
    'icon': 'http://assets.foodzie.com/media/catalog/category/snacks.png',
    'link': 'http://foodzie.com/snacks.html?ref=5',
    'desc': prefs.getMsg('snacks_desc')
  }
];

/**
 * Base url for all category.  CID is replaced with the category ID.
 * @type {string}
 */
// for debugging
var FEED_URL = 'http://www.adamsah.net/~asah/foodzie/foodziegadget/' +
    'cat-example.json?67';
FEED_URL = FEED_BASE + '/product/bycategory/cid/CID/template/json/limit/LIMIT';

/**
 * Gadget url.
 * @const
 */
var GADGET_LINK = 'http://foodziegadget.googlecode.com/svn/trunk/';

/**
 * Html template for loading icon.
 * @const
 */
var LOADING_TPL = '<div style="text-align:center">' +
    '<span class="foodzie-loading"><img id="imgload" ' +
    'src="http://www.google.com/ig/images/spinner.gif"/>&nbsp;&nbsp;' +
    prefs.getMsg('loading') + '</span></div>';

/**
 * Html template if the data is not available.
 * @const
 */
var TRY_AGAIN_TPL = '<div class="foodzie-refresh">' +
    prefs.getMsg('data_not_available') + '&nbsp;' +
    '<a href="javascript:void(0);" onclick="refreshTab();">' +
    prefs.getMsg('try_again') + '</a></div>';

/**
 * Collection of all the items for selected category.
 * @type {Array}
 */
var content = [];

/**
 * Gives the value of a node.
 * @param {Object} element Node element.
 * @return {string} Value of the node.
 */
function getNodeValue(element) {
  return element && element.firstChild ? element.firstChild.nodeValue : '';
}

/**
 * Parse data from feed responded by server.
 * @param {string} feedStr Response from server
 *     for the item selected.
 * @param {number} imgWidth Width of image.
 * @param {number} imgHeight Height of image.
 * @return {Object} Object containing data related to selected category.
 */
function parseFeed(feedStr, imgWidth, imgHeight) {
  // JSON don't like newlines in strings, go figure...
  feedStr = feedStr.replace(/[\r\n]/g, '');
  var feed = eval('(' + feedStr + ')');
  var data = [];
  for (var i = 0, len = feed.products.length; i < len; i++) {
    var obj = {};
    obj.title = feed.products[i].name;
    // remove 'The' -- less commercial, less space
    obj.title = obj.title.replace(/^[tT]he /, '');
    obj.snippet = feed.products[i].snippet;
    obj.link = feed.products[i].url;
    if (obj.link.indexOf('?') == -1) {
      obj.link += '?ref=5';
    } else {
      obj.link += '&ref=5';
    }
    // for development (harmless for production)
    obj.img = feed.products[i].image.replace(/dev3.local/, 'media.foodzie.com');
    // strip any CDN, if present
    obj.img = obj.img.replace(/^http:\/\/.+(https?)/, '$1');
    obj.imgwidth = imgWidth;
    obj.imgheight = imgHeight;
    obj.img = gadgets.io.getProxyUrl(obj.img);
    obj.price = '$' + feed.products[i].price.replace(/.00$/, '');
    data.push(obj);
  }
  return data;
}

/**
 * Shows the message.
 * @param {string} msg Message to be shown.
 */
function showMessage(msg) {
  var msgElement = _gel('foodzie-msg');
  msgElement.style.display = 'block';
  msgElement.innerHTML = msg;
  _gel('foodzie-content').style.display = 'none';
}

/**
 * Fetches the news feed and shows the result.
 * @param {string} feedUrl The url of feed.
 * @param {string} width Width of image container.
 * @param {string} height Height of image container.
 */
function fetchContent(feedUrl, width, height) {
  showMessage(LOADING_TPL);
  var timeoutId = setTimeout(function() {
    showMessage(TRY_AGAIN_TPL);
  }, TIME_OUT);
  _IG_FetchContent(feedUrl, function(feed) {
    clearTimeout(timeoutId);
    _gel('foodzie-msg').style.display = 'none';
    try {
      content = parseFeed(feed, width, height);
      createBody();
    } catch (err) {
      content = [];
      showMessage(TRY_AGAIN_TPL);
    }
  }, {refreshInterval: 60 * 15});
}
